package com.xoa.dev.pz.service;

import com.xoa.dao.common.SysCodeMapper;


import com.xoa.model.common.SysCode;

import com.xoa.model.users.Users;
import com.xoa.dev.pz.dao.MenuJdtMapper;
import com.xoa.dev.pz.dao.PzHouseMapper;
import com.xoa.dev.pz.dao.PzHouseRentMapper;
import com.xoa.dev.pz.dao.PzHouseServiceMapper;
import com.xoa.dev.pz.model.PzHouseRent;
import com.xoa.dev.pz.model.PzHouseWithBLOBs;
import com.xoa.service.users.UsersService;
import com.xoa.dao.party.IllegalrentgroupMapper;
import com.xoa.model.party.GridCheck;
import com.xoa.model.party.Illegalrentgroup;
import com.xoa.util.DateFormat;
import com.xoa.util.ExcelUtil;
import com.xoa.util.ToJson;
import com.xoa.util.common.L;
import com.xoa.util.common.StringUtils;
import com.xoa.util.common.log.FileUtils;
import com.xoa.util.common.session.SessionUtils;
import com.xoa.util.netdisk.CheckAll;
import com.xoa.util.page.PageParams;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.OutputStream;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service

public class PzHouseService {
    @Resource
    private PzHouseMapper pzHouseMapper;


    @Resource
    private MenuJdtMapper menuJdtMapper;
    @Resource
    private UsersService usersService;

    @Resource
    private PzHouseRentMapper pzHouseRentMapper;

    @Resource
    private PzHouseServiceMapper pzHouseServiceMapper;

    @Resource
    private SysCodeMapper sysCodeMapper;

    @Resource
    private IllegalrentgroupMapper illegalrentgroupMapper;

    /**
     * 增加
     * @param pzHouseWithBLOBs
     * @return
     */
    @Transactional
    public ToJson insertHouse(PzHouseWithBLOBs pzHouseWithBLOBs, PzHouseRent pzHouseRent){
        ToJson<PzHouseWithBLOBs> toJson=new ToJson<PzHouseWithBLOBs>(1,"error");
        int temp=0;
        if(pzHouseMapper.selHouseByLocation(pzHouseWithBLOBs.getHouseLocation())==null){
            temp+=pzHouseMapper.insertSelective(pzHouseWithBLOBs);
            if(!StringUtils.checkNull(pzHouseWithBLOBs.getHouseIsRent()) && pzHouseWithBLOBs.getHouseIsRent().equals("2")){
                pzHouseRent.setRentHouseId(pzHouseWithBLOBs.getHouseId());
                temp+=pzHouseRentMapper.insertSelective(pzHouseRent);
            }
            if("2".equals(pzHouseRent.getHouseIsRent()) ){
                Illegalrentgroup illegalrentgroup=new Illegalrentgroup();
                illegalrentgroup.setSubArea(pzHouseRent.getGridName());
                illegalrentgroup.setBuildingDoor(pzHouseRent.getHouseLocation());
                illegalrentgroup.setSubArea(String.valueOf(pzHouseRent.getGridId()));
                illegalrentgroup.setSubStreet("邳州市岔河镇");
                temp+=illegalrentgroupMapper.insertSelective(illegalrentgroup);
            }
        }else{
            toJson.setMsg("location");
        }
        if(temp>0){
            toJson.setFlag(0);
            toJson.setMsg("success");
        }
        return toJson;
    }

    /**
     * 删除
     * @param houseId
     * @return
     */
    @Transactional
    public ToJson delHouse(int houseId){
        ToJson toJson=new ToJson(1,"error");
        int temp=pzHouseMapper.deleteByPrimaryKey(houseId);
        Map<String,Object> map=new HashMap<>();
        PzHouseRent rent=new PzHouseRent();
        rent.setRentHouseId(houseId);
        map.put("pzHouseRent",rent);
        List<PzHouseRent> pzHouseRentList=pzHouseRentMapper.selectRentOrderByrentConcern(map);
        for(PzHouseRent pzHouseRent:pzHouseRentList){
            if(pzHouseRent.getRentId()!=null){
                temp+=pzHouseServiceMapper.delServiceByRentId(pzHouseRent.getRentId());//先删除出租屋服务信息
            }
        }
        //再删除出租屋信息
        temp+=pzHouseRentMapper.deleteByHouseId(houseId);
        if(temp>0){
            toJson.setFlag(0);
            toJson.setMsg("success");
        }
        return toJson;
    }

    /**
     * 修改
     * @param pzHouseWithBLOBs
     * @return
     */
    @Transactional
    public ToJson upHouse(PzHouseWithBLOBs pzHouseWithBLOBs, PzHouseRent pzHouseRent, HttpServletRequest request){
        ToJson toJson=new ToJson<>(1,"error");
        PzHouseWithBLOBs before=pzHouseMapper.selectByPrimaryKey(pzHouseWithBLOBs.getHouseId());
        int temp=0;
        if(before.getHouseLocation().equals(pzHouseWithBLOBs.getHouseLocation()) || pzHouseMapper.selHouseByLocation(pzHouseWithBLOBs.getHouseLocation())==null){
            temp=pzHouseMapper.updateByPrimaryKeySelective(pzHouseWithBLOBs);
            if(!StringUtils.checkNull(pzHouseWithBLOBs.getHouseIsRent()) && pzHouseWithBLOBs.getHouseIsRent().equals("1")){
                temp+=pzHouseRentMapper.deleteByHouseId(pzHouseWithBLOBs.getHouseId());
            }else if(!StringUtils.checkNull(pzHouseWithBLOBs.getHouseIsRent()) && pzHouseWithBLOBs.getHouseIsRent().equals("2")){
                pzHouseRent.setRentHouseId(pzHouseWithBLOBs.getHouseId());
                if(pzHouseRentMapper.selRentByHouseId(pzHouseWithBLOBs.getHouseId())!=null){
                    temp+=pzHouseRentMapper.updateRentByHouseId(pzHouseRent);
                }else{
                    Users user= SessionUtils.getSessionInfo(request.getSession(), Users.class, new Users());
                    pzHouseRent.setCreateUser(user.getUserId());
                    pzHouseRent.setCreateTime(DateFormat.getDatestr(new Date()));
                    temp+=pzHouseRentMapper.insertSelective(pzHouseRent);
                }
            }
        }else{
            toJson.setMsg("location");
        }
        if(temp>0){
            toJson.setFlag(0);
            toJson.setMsg("success");
        }
        return toJson;
    }

    /**
     * 查询
     * @param
     * @return
     */
    @Transactional
    public ToJson selectHouse(Integer page, Integer pageSize, boolean useFlag, PzHouseWithBLOBs pzHouseWithBLOBs, int output, HttpServletResponse response, HttpServletRequest request){
        ToJson<PzHouseWithBLOBs> toJson=new ToJson<>(1,"error");
        try{
            PageParams pageParams=new PageParams();
            pageParams.setPage(page);
            pageParams.setPageSize(pageSize);
            pageParams.setUseFlag(useFlag);
            Map<String, Object> map = new HashMap<String, Object>();

            map.put("pzHouseWithBLOBs",pzHouseWithBLOBs);
            Users user = SessionUtils.getSessionInfo(request.getSession(), Users.class,new Users());
            String menuModel=menuJdtMapper.selMenuByModel("1");
            Map<String, Object> param = new HashMap<String, Object>();
            param.put("userId", user.getUserId());
            param.put("userPriv", user.getUserPriv());
            param.put("deptId", user.getDeptId());
            GridCheck gridCheck1=new GridCheck();
            if(!CheckAll.checkAll(menuModel,param)){
                map.put("createUser",user.getUserId());
            }
            toJson.setTotleNum(pzHouseMapper.selCountByPzHouseMap(map));
            map.put("page", pageParams);
            List<PzHouseWithBLOBs> list=pzHouseMapper.selectByPzHouseWithBLOBs(map);

            for(PzHouseWithBLOBs pzHouseWithBLOBs1:list){
                if(!StringUtils.checkNull(pzHouseWithBLOBs1.getGridUserId())){
                    pzHouseWithBLOBs1.setUserName(usersService.getUserNameById(pzHouseWithBLOBs1.getGridUserId()));
                }
                SysCode purposeCode = sysCodeMapper.getSingleCode("HOUSE_PURPOSE", pzHouseWithBLOBs1.getHousePurpose());
                if(purposeCode!=null){
                    pzHouseWithBLOBs1.setHousePurposeStr(purposeCode.getCodeName());
                }
                SysCode makeupCode = sysCodeMapper.getSingleCode("HOUSE_MAKEUP", pzHouseWithBLOBs1.getHouseMakeup());
                if(makeupCode!=null){
                    pzHouseWithBLOBs1.setHouseMakeupStr(makeupCode.getCodeName());
                }
                SysCode applicationCode = sysCodeMapper.getSingleCode("HOUSE_APPLICATION", pzHouseWithBLOBs1.getHouseApplication());
                if(applicationCode!=null){
                    pzHouseWithBLOBs1.setHouseApplicationStr(applicationCode.getCodeName());
                }
                SysCode sourceCode = sysCodeMapper.getSingleCode("HOUSE_SOURCE", pzHouseWithBLOBs1.getHouseSource());
                if(sourceCode!=null){
                    pzHouseWithBLOBs1.setHouseSourceStr(sourceCode.getCodeName());
                }
            }
            if(output==1){
                for(PzHouseWithBLOBs pzHouseWithBLOBs1:list){
                   if(!StringUtils.checkNull(pzHouseWithBLOBs1.getHouseType())){
                       if(pzHouseWithBLOBs1.getHouseType().equals("1")){
                           pzHouseWithBLOBs1.setHouseType("商品房");
                       }else{
                           pzHouseWithBLOBs1.setHouseType("其他");
                       }
                   }
                }
                HSSFWorkbook tableWork = ExcelUtil.makeExcelHead("房屋表", 15);
                String[] secondTitles = {"所属网络","建筑名称", "房屋区别类型","房屋地址","建筑用途","建成年份","房屋结构","房屋户型","建筑面积","房屋用途","房屋来源","房主","房主证件号码","房主联系方式","房主现居地址","备注"};
                HSSFWorkbook excelWork = ExcelUtil.makeSecondHead(tableWork, secondTitles);
                String[] beanProperty = {"gridName","houseName","houseType","houseLocation","housePurposeStr","houseYear","houseMakeupStr","houseStyle","houseArea","houseApplicationStr","houseSourceStr","houseUsername","houseIdcard","houseTelno","houseNowsite","houseMemo"};
                HSSFWorkbook workbook = ExcelUtil.exportExcelData(excelWork, list, beanProperty);
                response.setContentType("text/html;charset=UTF-8");
                OutputStream out = response.getOutputStream();

                String filename = "房屋信息表.xls"; //考虑多语言
                filename = FileUtils.encodeDownloadFilename(filename,
                        request.getHeader("user-agent"));
                response.setContentType("application/vnd.ms-excel");
                response.setHeader("content-disposition",
                        "attachment;filename=" + filename);
                workbook.write(out);
                out.flush();
                out.close();
            }
            toJson.setObj(list);
            toJson.setMsg("success");
            toJson.setFlag(0);
        }catch (Exception e){
            toJson.setMsg(e.getMessage());
            L.e("PzHouseService PzHouseService:"+e);
            e.printStackTrace();
        }
        return toJson;
    }

    public ToJson selectHouseByHouseId(HttpServletRequest request, Integer houseId){
        ToJson<PzHouseWithBLOBs> toJson=new ToJson<>(1,"error");
        PzHouseWithBLOBs pzHouse=pzHouseMapper.selectByPrimaryKey(houseId);
        PzHouseRent pzHouseRent=pzHouseRentMapper.selRentByHouseId(houseId);
        pzHouse.setPzHouseRent(pzHouseRent);
        if(!StringUtils.checkNull(pzHouse.getGridUserId())){
            pzHouse.setUserName(usersService.getUserNameById(pzHouse.getGridUserId()));
        }
        SysCode purposeCode = sysCodeMapper.getSingleCode("HOUSE_PURPOSE", pzHouse.getHousePurpose());
        if(purposeCode!=null){
            pzHouse.setHousePurposeStr(purposeCode.getCodeName());
        }
        SysCode makeupCode = sysCodeMapper.getSingleCode("HOUSE_MAKEUP", pzHouse.getHouseMakeup());
        if(makeupCode!=null){
            pzHouse.setHouseMakeupStr(makeupCode.getCodeName());
        }
        SysCode applicationCode = sysCodeMapper.getSingleCode("HOUSE_APPLICATION", pzHouse.getHouseApplication());
        if(applicationCode!=null){
            pzHouse.setHouseApplicationStr(applicationCode.getCodeName());
        }
        SysCode sourceCode = sysCodeMapper.getSingleCode("HOUSE_SOURCE", pzHouse.getHouseSource());
        if(sourceCode!=null){
            pzHouse.setHouseSourceStr(sourceCode.getCodeName());
        }
        toJson.setObject(pzHouse);
        toJson.setFlag(0);
        toJson.setMsg("ok");
        return toJson;
    }


 /*   *//**
     * 创建作者:   牛江丽
     * 创建日期:   2017年12月11日 下午16:02:00
     * 方法介绍:   房屋导入
     * 参数说明:
     * 返回值说明:
     *//*
    @Transactional
    public  ToJson<PzHouseWithBLOBs> inputPzHouse(HttpServletRequest request, HttpServletResponse response, MultipartFile file, HttpSession session) {
        ToJson<PzHouseWithBLOBs> json = new ToJson<PzHouseWithBLOBs>(1, "error");
        try {
            //判读当前系统
            //读取配置文件
            ResourceBundle rb = ResourceBundle.getBundle("upload");
            //String name = rb.getString("mysql.driverClassName");
            String osName = System.getProperty("os.name");
            StringBuffer path = new StringBuffer();
            if (osName.toLowerCase().startsWith("win")) {
                path = path.append(rb.getString("upload.win"));
            } else {
                path = path.append(rb.getString("upload.linux"));
            }
            if (file.isEmpty()) {
                json.setMsg("请上传文件！");
                return json;
            } else {
                int count=0;
                String fileName = file.getOriginalFilename();
                if (fileName.endsWith(".xls") || fileName.endsWith(".xlsx")) {
                    String uuid = UUID.randomUUID().toString();
                    uuid = uuid.replaceAll("-", "");
                    int pos = fileName.indexOf(".");
                    String extName = fileName.substring(pos);
                    String newFileName = uuid + extName;
                    File dest = new File(path.toString(), newFileName);
                    *//*file.transferTo(dest);*//*
                    //将文件上传成功后进行读取文件
                    //进行读取的路径
                    String readPath = path.append(newFileName).toString();
                    InputStream in = new FileInputStream(readPath);
                    HSSFWorkbook excelObj = new HSSFWorkbook(in);
                    HSSFSheet sheetObj = excelObj.getSheetAt(0);
                    Row rowObj = null;
                    int lastRowNum = sheetObj.getLastRowNum();
                    int inputFail=0;
                    int inputSuccess=0;
                    String faillReason="";
                    for (int i = 2; i <= lastRowNum; i++) {
                        rowObj = sheetObj.getRow(i);
                        if (rowObj != null) {
                            Cell c0 = rowObj.getCell(0);
                            Cell c1 = rowObj.getCell(1);
                            Cell c2 = rowObj.getCell(2);
                            Cell c3 = rowObj.getCell(3);
                            Cell c4 = rowObj.getCell(4);
                            Cell c5 = rowObj.getCell(5);
                            Cell c6 = rowObj.getCell(6);
                            Cell c7 = rowObj.getCell(7);
                            Cell c8 = rowObj.getCell(8);
                            Cell c9 = rowObj.getCell(9);
                            Cell c10 = rowObj.getCell(10);
                            Cell c11 = rowObj.getCell(11);
                            Cell c12 = rowObj.getCell(12);
                            Cell c13 = rowObj.getCell(13);
                            Cell c14 = rowObj.getCell(14);
                            Cell c15 = rowObj.getCell(15);
                            PzHouseWithBLOBs pzHouse = new PzHouseWithBLOBs();
                            if (c0.getStringCellValue() != "" && c2.getStringCellValue() != "" && c3.getStringCellValue() != "") {
                                GridInfo gridInfo = gridInfoMapper.selectByUGridName(c0.getStringCellValue());
                                if (gridInfo != null) {
                                    pzHouse.setGridName(String.valueOf(gridInfo.getGridId()));
                                }
                                pzHouse.setHouseName(c1.getStringCellValue());
                                String c2Value = c2.getStringCellValue();
                                if (c2Value.equals("商品房")) {
                                    pzHouse.setHouseType("0");
                                } else {
                                    pzHouse.setHouseType("1");
                                }
                                String c3Value = c3.getStringCellValue();
                                String localtion1 = c3Value.replace("小区", ",");
                                String localtion2 = localtion1.replace("幢", ",");
                                String localtion3 = localtion2.replace("单元", ",");
                                String localtion4 = localtion3.replace("室", "");
                                pzHouse.setHouseLocation(localtion4);
                                String c4Value = c4.getStringCellValue();
                                if (c4Value.equals("0")) {
                                    pzHouse.setHousePurpose("住宅");
                                } else if (c4Value.equals("1")) {
                                    pzHouse.setHousePurpose("商业");
                                } else if (c4Value.equals("2")) {
                                    pzHouse.setHousePurpose("办公");
                                } else if (c4Value.equals("3")) {
                                    pzHouse.setHousePurpose("工业");
                                } else if (c4Value.equals("4")) {
                                    pzHouse.setHousePurpose("综合");
                                } else {
                                    pzHouse.setHousePurpose("其他");
                                }
                                pzHouse.setHouseYear(c5.getStringCellValue());
                                pzHouse.setHouseMakeup(c6.getStringCellValue());
                                pzHouse.setHouseStyle(c7.getStringCellValue());
                                pzHouse.setHouseArea(c8.getStringCellValue());
                                String c9Value = c9.getStringCellValue();
                                if (c9Value.equals("0")) {
                                    pzHouse.setHouseApplication("个人住宅");
                                } else if (c9Value.equals("1")) {
                                    pzHouse.setHouseApplication("集团宿舍");
                                } else if (c9Value.equals("2")) {
                                    pzHouse.setHouseApplication("临时工棚");
                                } else if (c9Value.equals("3")) {
                                    pzHouse.setHouseApplication("办公用房");
                                } else if (c9Value.equals("4")) {
                                    pzHouse.setHouseApplication("商业用房");
                                } else if (c9Value.equals("5")) {
                                    pzHouse.setHouseApplication("其他民用用房");
                                } else if (c9Value.equals("6")) {
                                    pzHouse.setHouseApplication("简易棚");
                                } else {
                                    pzHouse.setHouseApplication("其他");
                                }
                                String c10Value = c10.getStringCellValue();
                                if (c10Value.equals("0")) {
                                    pzHouse.setHouseSource("自由产主");
                                } else if (c10Value.equals("1")) {
                                    pzHouse.setHouseSource("租赁公司");
                                }
                                pzHouse.setHouseUsername(c11.getStringCellValue());
                                pzHouse.setHouseIdcard(c12.getStringCellValue());
                                pzHouse.setHouseTelno(Long.valueOf(c13.getStringCellValue()));
                                pzHouse.setHouseNowsite(c14.getStringCellValue());
                                pzHouse.setHouseMemo(c15.getStringCellValue());
                                count=pzHouseMapper.insertSelective(pzHouse);
                            }
                        }
                    }
                    json.setTotleNum(count);
                    json.setFlag(0);
                    json.setMsg("ok");
                    dest.delete();
                } else {
                    json.setMsg("0");//文件类型不正确
                    return json;
                }
            }
        } catch (Exception e) {
            json.setMsg(e.getMessage());
            L.e("EduFixAssetsService inputFixAsserts:"+e);
            e.printStackTrace();
        }
        return json;
    }*/
}
